﻿using System.Linq;
using HmBuild;
using Microsoft.Office.Interop.Excel;

namespace HmLab.Func2;

internal class LbFillMonthResult {

  /// <summary>
  /// FillResult(string
  /// <see cref="Haimen.Func2.MonthResultMaker"/>
  /// <see cref="Program.Main"/>
  /// </summary>
  public void Run() {
    System.Console.WriteLine("----LbFillMonthResultLbFillMonthResult");

    string resultPath = @"D:\work\personal\nina\2023haimen2\workshop_cslab\输Q出f2\月合并报表.xlsx";
    var StoreFile = (string f) => PathX
      .Of(@"D:\work\personal\nina\2023haimen2\workshop_cslab\输O入0206f2\店铺分表")
      .Resolve(f)
      .ToString();

    MonthStoreIn[] inputList = [
      new(StoreFile("粤垦店-2023年12期月报.xls"), "A1:Z69", "粤垦"),
      //new(StoreFile("五羊店利润表-2023年12期月报.xlsx"), "A1:Z69", "五羊"),
      //new(StoreFile("小潮-2023年12期月报.xlsx"), "A1:U68", "小潮"),
    ];

    foreach (var aaa in MakeCopyArg(inputList)) {
      System.Console.WriteLine(aaa.Path);
      foreach (var bbb in aaa.Sheets) {
        System.Console.WriteLine(" - " + bbb.Name);
        foreach (var ccc in bbb.From) {
          System.Console.WriteLine("  * " + (ccc.Name ?? "[Sheet:1]"));
          foreach (var ddd in ccc.Cells) {
            System.Console.WriteLine($"   # {ddd.FromRange} -> {ddd.ToCell}");
          }
        }
      }
    }

    Application excelApp = new() {
      Visible = true,
      ScreenUpdating = false,
    };

    Workbooks books = excelApp.Workbooks;
    Workbook toBook = books.Open(resultPath, UpdateLinks: false);

    excelApp.DisplayAlerts = false;
    BookFrom[] copyArg = MakeCopyArg(inputList);
    _interopCopier.Copy(toBook, copyArg);

    excelApp.ScreenUpdating = true;
  }

  BookFrom[] MakeCopyArg(MonthStoreIn[] inputList) {
    var MakeBook = (MonthStoreIn input) => {
      CellCopy cellArg = new(FromRange: input.Range, ToCell: "A1");
      SheetTo sheetTo = new(input.ToSheet, From: [new(null, [cellArg])]);
      return new BookFrom(input.Path, [sheetTo]);
    };

    return inputList
      .Select(MakeBook)
      .ToArray();
  }

  record MonthStoreIn(string Path, string Range, string ToSheet);

  readonly LbExcelCopyRange.Copier _interopCopier = new(new());
}
